import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, message, Upload, Modal, Cascader } from 'antd';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { getBase64, reduceProvArr } from '@/utils/utils';
import type { FromUserType, ManageUserProps, ProvinceType } from './src/data';
import { PlusOutlined } from '@ant-design/icons';
import type { RoleType } from '@/services/role';
import { queryRole } from '@/services/role';
import { getProvince } from '@/services/global';
import styles from './manageUser.less';
import { createUser, findCurrent, updateUser } from '@/services/user';
import { useLocation, history } from 'umi';

const ManageUser: React.FC<ManageUserProps> = () => {
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);
  const [previewImage, setPreviewImage] = useState<string>('');
  const [previewTitle, setPreviewTitle] = useState<string>('');
  const [province, setProvince] = useState<any>([]);
  const location: any = useLocation<any>();
  const [title, setTitle] = useState<string>('创建用户');
  const [fileList, setFileList] = useState<any[]>([]);
  const [form] = ProForm.useForm();

  useEffect(() => {
    const getData = async () => {
      const res = await getProvince();
      if (res) {
        const provArr: ProvinceType[] = [];
        reduceProvArr(res?.data, provArr);
        setProvince(provArr);
      }
      if (location?.query?.type === 'edit') {
        setTitle('编辑用户');
        const resUser = await findCurrent({ _id: location?.state?.id });
        if (resUser) {
          form.setFieldsValue(resUser.data);
          setFileList(resUser.data.avatar ? resUser.data.avatar : []);
          setPreviewImage(resUser.data.avatar?.[0]?.url);
        }
      }
    };
    getData();
  }, []);

  const handleCancel = () => setPreviewVisible(false);

  const handlePreview = async (file: any) => {
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    setPreviewVisible(true);
  };

  const handleChangeFile = async (val: any) => {
    setFileList(val?.fileList);
    const { file } = val;
    const { status } = file;
    if (status === 'done') {
      if (!file.url && !file.preview) {
        // eslint-disable-next-line no-param-reassign
        file.preview = await getBase64(file.originFileObj);
      }
      setPreviewImage(file.url || file.preview);
    } else {
      setPreviewImage('');
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <PageContainer className={styles.manageUser}>
      <Card>
        <h3>{title}</h3>
        <ProForm<FromUserType>
          className={styles.form}
          form={form}
          layout="horizontal"
          labelCol={{ span: 2 }}
          validateTrigger={['onChange', 'onFocus', 'onBlur']}
          initialValues={{
            roleName: 'user',
          }}
          submitter={{
            // 配置按钮的属性
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                marginLeft: '50px',
              },
            },
          }}
          onFinish={async (values) => {
            const getAvatar = () => {
              if (values?.avatar?.file?.preview) {
                return values?.avatar?.file.preview;
              }
              return values?.avatar?.fileList?.length === 0 ? '' : values?.avatar;
            };
            const val = values?.avatar
              ? {
                  ...values,
                  avatar: getAvatar(),
                }
              : values;
            if (location?.query?.type === 'edit') {
              const res = await updateUser({ ...val, _id: location?.state?.id });
              if (res) {
                history.push('/manager/userManager/find');
                message.success(res.message);
              }
            } else {
              const res = await createUser(val);
              if (res) {
                message.success(res.message);
                history.push('/manager/userManager/find');
              }
            }
          }}
          params={{}}
          // request={async () => {
          //   const res = await createUser(100);
          //   return res?.data;
          // }}
        >
          <ProFormText
            width="md"
            name="userName"
            label="用户名"
            hasFeedback
            placeholder="请输入用户名"
            rules={[
              {
                required: true,
                message: '用户名不能为空',
              },
            ]}
          />
          <ProFormText
            width="md"
            name="email"
            label="邮箱"
            hasFeedback
            validateFirst
            placeholder="请输入邮箱"
            rules={[
              {
                required: true,
                message: '邮箱不能为空',
              },
              {
                validator: (rule, value) => {
                  const match = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                  if (!match.test(value)) {
                    return Promise.reject(new Error('邮箱格式不正确！'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          />
          <ProFormText
            width="md"
            name="phone"
            hasFeedback
            label="手机号"
            placeholder="请输入手机号"
            validateFirst
            rules={[
              {
                required: true,
                message: '手机号不能为空',
              },
              {
                validator: (rule, value) => {
                  const match = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
                  if (!match.test(value)) {
                    return Promise.reject(new Error('手机号格式不正确！'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          />
          {location?.query?.type !== 'edit' && (
            <ProFormText.Password
              width="md"
              name="password"
              label="密码"
              hasFeedback
              placeholder="请输入密码"
              help="密码包含 数字,英文,字符中的两种以上，长度6-20"
              validateFirst
              rules={[
                {
                  required: true,
                  message: '密码不能为空',
                },
                {
                  validator: (rule, value) => {
                    const match =
                      /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{6,20}$/;
                    if (!match.test(value)) {
                      return Promise.reject(
                        new Error('密码包含 数字,英文,字符中的两种以上，长度6-20'),
                      );
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            />
          )}
          {location?.query?.type !== 'edit' && (
            <ProFormText.Password
              width="md"
              name="confirm"
              label="确认密码"
              hasFeedback
              placeholder="请再次输入密码"
              validateFirst
              rules={[
                {
                  required: true,
                  message: '确认密码不能为空',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }

                    return Promise.reject(new Error('两次密码不相同!'));
                  },
                }),
              ]}
            />
          )}
          <ProForm.Item label="头像" name="avatar">
            <Upload
              fileList={fileList}
              // action="/api/manage/img/upload"
              // showUploadList={false}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              maxCount={1}
              listType="picture-card"
              onPreview={handlePreview}
              onChange={handleChangeFile}
            >
              {!previewImage && uploadButton}
            </Upload>
          </ProForm.Item>
          <ProForm.Item
            hasFeedback
            label="地址"
            name="address"
            dependencies={['detailAddress']}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (getFieldValue('detailAddress') && (!value || value.length === 0)) {
                    return Promise.reject(new Error('请输入选择地址!'));
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Cascader options={province} placeholder="请选择地址" />
          </ProForm.Item>
          <ProFormText
            width="md"
            name="detailAddress"
            label="详细地址"
            // help="选了地址就必须填写详细地址"
            placeholder="请输入详细地址"
          />
          <ProFormSelect
            hasFeedback
            placeholder="请选择角色"
            width="md"
            request={async () => {
              const resRole = await queryRole();
              if (resRole) {
                return resRole.data?.map((item: RoleType) => {
                  // eslint-disable-next-line no-underscore-dangle
                  return { value: item.name, label: item.name, key: item._id };
                });
              }
              return null;
            }}
            name="roleName"
            label="角色"
            rules={[
              {
                required: true,
                message: '请选择角色',
              },
            ]}
          />
        </ProForm>
        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
          <img alt="头像" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default ManageUser;
